package com.juzipi.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author juzipi
 * @Date 2021/7/30 10:33
 * @Info
 */
@Component
public class MailService {

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 发送html邮件
     * @param email 邮箱
     * @param subject 主题
     * @param template 模板
     * @return
     */
    public Boolean sendRemindEmail(String email,String subject,String template){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setTo(email);//接收方
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(template,true);
            javaMailSender.send(mimeMessage);
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            System.out.println("邮件发送成功 ------------> "+email+" "+ format);
            return true;
        } catch (MessagingException e) {
            System.out.println("发送邮件失败 ------------> "+e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
